from playwright.sync_api import expect
import json
from Config.config import *

import re
import allure, os
from Config.Base import Base
from Config.Tool import tool
from Config.Base import Base
from Config.URL import *
from Config.Tool import tool

def autoflow(Base : Base,flowtitle):

    #存储cookie
    playwright = Base.p
    browser = Base.browser
    context = Base.context
    page = Base.page
    context.storage_state(path=cookie_dir+"cookie.json")

    # 计量支付列表
    if page.get_by_text("计量状态： 等待审核").is_visible():
        page.get_by_text("等待审核").click()
    # 质量验评
    #page.locator("section div").filter(has_text=re.compile(r"^质量验评$"))
    elif page.locator("#tags-view-container").get_by_text("质量验评").is_visible():
        page.get_by_role("cell", name=flowtitle).click()
    # 常规列表
    elif page.get_by_role("row", name=flowtitle).first.is_visible():
        page.get_by_role("row", name=flowtitle).first.click(click_count=2)


    # 1.点击发起流程数据
    #page.get_by_label("待办事宜").get_by_text("【施工安全日志】 2024-03-09施工安全日志").click()
    # 2.监控流程接口，获取流程接口
    # 监听请求事件
    #page.on("request", lambda request: print("request: ", request.method, request.url))
    # 监听响应事件
    #page.on("response", lambda response: print("response: ", response.status, response.url))
    page.on("response", lambda response: Base.seturl(response.url))
    page.wait_for_timeout(2000)
    # 3.解析接口获取审批人
    # 读取cookie JSON文件
    with open(cookie_dir+"cookie.json", 'r', encoding='utf-8') as f:
        data = json.load(f)
        print(data)

    # 寻找cookie位置
    cookieInLists = data["origins"][0]["localStorage"]
    cookieIndex = 10000
    for list in cookieInLists:
        if list["name"] == "pit_token":
            cookieIndex = cookieInLists.index(list)
            break
    if cookieIndex == 10000:
        print("！！！未提取到cookie数据！！！")
    # 提取cookie数据--给接口使用（这里只是打印出来）
    cookie = cookieInLists[cookieIndex]["value"]
    print(cookie)
    # cookie后缀带|String--删除掉
    webcookie = cookie.replace("|String", "")
    head = {
        # "Accept": "application/json, text/plain, */*",
        # Add GitHub personal access token.
        "Authorization": webcookie,
    }
    #context = playwright.request.new_context(base_url='http://172.18.3.26:7300')
    httpcontext = playwright.request.new_context()
    response = httpcontext.get(url = Base.geturl(),headers=head)
    responsejson = response.json()
    print("解析接口获取审批人:")
    print(responsejson)
    #while len(responsejson["data"]["runTask"]) != 0:
    while len(httpcontext.get(url = Base.geturl(),headers=head).json()["data"]["runTask"]) != 0:
        peoples = []
        peopleCount = httpcontext.get(url = Base.geturl(),headers=head).json()["data"]["runTask"]
        for person in peopleCount:
            peoples.append(person["handledDtoList"][0]["handledByName"])
        #people = responsejson["data"]["runTask"][0]["handledDtoList"][0]["handledByName"]
        node = httpcontext.get(url = Base.geturl(),headers=head).json()["data"]["runTask"][0]["signDeployDTO"]["signKeyword"]
        print("下节点审批人：" + f'{peoples}' + "   节点：" + node)
        # 4.审批人转换为账号
        approvalpeople = ''
        if "陈凯" in peoples:
            approvalpeople = "shigong1"
            print("审批使用账户： " + approvalpeople)
        elif "谭监" in peoples:
             approvalpeople = "jianli1"
             print("审批使用账户： " + approvalpeople)
        else:
            approvalpeople = "admin"
            print("审批使用账户： " + approvalpeople)
        # for people in peoples:
        #     if people == "陈凯":
        #         approvalpeople = "shigong1"
        #         print("审批使用账户： " + approvalpeople)
        #         break
        #     elif people == "谭监":
        #         approvalpeople = "jianli1"
        #         print("审批使用账户： " + approvalpeople)
        #         break
        #     elif people == "管理员":
        #         approvalpeople = "admin"
        #         print("审批使用账户： " + approvalpeople)
        #         break
        #
        if approvalpeople == '':
            approvalpeople = peoples[0]
            print("！！！审批人里没有找到配对人员，使用流程账号审批： " + approvalpeople)

        # 5.登录审批人账号，进行审批（通过cookies登录）
        context.close()
        # context = browser.new_context(storage_state="cookie.json")
        context = browser.new_context(viewport={'width': 1920, 'height': 1080})
        page = context.new_page()
        page.goto(url + url_login)
        page.get_by_placeholder("请输入用户名").fill(approvalpeople)
        page.get_by_placeholder("请输入密码").fill(password_admin)
        page.get_by_role("button", name="登 录").click()
        


        page.get_by_role("row", name=flowtitle).locator("span").nth(1).click()
        page.wait_for_timeout(2000)

        if page.get_by_role("button", name="通 过").is_visible():
            if page.get_by_placeholder("请输入签署密码").is_visible():
                page.get_by_placeholder("请输入签署密码").fill(password_flow)
            if page.get_by_placeholder("请选择签章").is_visible():
                page.get_by_placeholder("请选择签章").click()
                page.get_by_placeholder("请选择签章").press("ArrowDown")
                page.get_by_placeholder("请选择签章").press("Enter")
                # page.get_by_text("监理单位项目1部-企业公章").click()
            if page.get_by_placeholder("请选择签字时间").is_visible():
                page.get_by_placeholder("请选择签字时间").fill(tool.nowtime("ymd"))
                page.get_by_placeholder("请选择签字时间").press("Enter")

            page.get_by_role("button", name="通 过").click()
            # 质量验评
            page.wait_for_timeout(1000)
            if page.get_by_text("当前报表是否已经填报？").is_visible():
                page.get_by_role("button", name="确定").click()
            # 质量验评
            tips = page.locator("xpath=//p[@class=\"el-message__content\"]").text_content()  # 获取元素上的文本
            if tips == "请求成功" or tips == "审批成功!":
                continue
            elif tips == "请先填报业务表单":
                # 在线表单填报
                # page.locator("div").filter(has_text=re.compile(r"^测量方案报审$")).first.click()
                trcount = page.get_by_text("业务表单新增表单表单填报").locator("//table/tbody/tr").count()
                print("业务表单填报："+ str(trcount))
                for tr in page.get_by_text("业务表单新增表单表单填报").locator("//table/tbody/tr").all():
                    page.get_by_text("未填报").first.click()
                    page.get_by_role("button", name=" 表单填报").click()
                    page.wait_for_timeout(1000)
                    if page.get_by_role("button", name="保存").is_visible():
                        page.get_by_role("button", name="保存").click()
                        expect(page.locator("body")).to_contain_text("填报成功")
                    elif page.get_by_text("上传填报后文件").is_visible():
                        page.get_by_text("上传填报后文件").click()
                        #page.locator("div").filter(has_text=re.compile(r"^上传填报后文件$")).nth(2).click()

                        with page.expect_file_chooser() as fc_info:
                            page.get_by_text("上传填报后文件").click()
                        file_chooser = fc_info.value
                        file_chooser.set_files(test_datas_dir + "\填报.docx")
                        expect(page.locator("body")).to_contain_text("导入成功")

                # page.get_by_text("未填报").first.click()
                # page.get_by_role("button", name=" 表单填报").click()
                # page.get_by_role("button", name="保存").click()
                # expect(page.locator("body")).to_contain_text("填报成功")
                # page.get_by_role("cell", name="CB01-").locator("div").click()
                # page.get_by_role("button", name=" 表单填报").click()
                # page.get_by_label("表单填报").locator("i").nth(2).click()
                # with page.expect_file_chooser() as fc_info:
                #     page.locator("div").filter(has_text=re.compile(r"^上传填报后文件$")).nth(2).click()
                # file_chooser = fc_info.value
                # file_chooser.set_files(test_datas_dir + "\填报.docx")
                # expect(page.locator("body")).to_contain_text("导入成功")
            elif tips == "上传文件并勾选需要签章":
                if page.get_by_role("button", name=" 新建").is_visible():
                    page.get_by_role("button", name=" 新建").click()
                    page.get_by_label("附件").locator("div").filter(has_text=re.compile(r"^是否签章$")).locator(
                        "span").click()
                    with page.expect_file_chooser() as fc_info:
                        page.get_by_label("附件").get_by_role("button", name="上传文件").click()
                    file_chooser = fc_info.value
                    file_chooser.set_files(test_datas_dir + "\签章.pdf")
                    page.wait_for_timeout(2000)
                    page.get_by_role("button", name="确定").click()
            elif tips == "当前文件还没进行签字盖章" or tips == "当前用户未签署完成":
                # 手动签字盖章
                if page.get_by_role("button", name="手动签字盖章").is_visible():
                    with page.expect_popup() as page1_info:
                        page.get_by_role("button", name="手动签字盖章").click()
                    page1 = page1_info.value
                    page1.get_by_role("img").first.drag_to(page1.locator(".pdf-viewer-page"))
                    page1.get_by_role("button", name="确认签署").click()
                    page1.get_by_role("textbox", name="请输入6位数字密码").click()
                    page1.get_by_role("textbox", name="请输入6位数字密码").fill(password_flow)
                    page1.get_by_role("button", name="完成签署").click()
                    page1.close()
                    page.wait_for_timeout(500)
            elif tips == "凭证明细中存在不同意/待审的记录，请标记审核状态后通过或者驳回!":
                page.wait_for_timeout(1000)
                if page.get_by_role("button", name=" 全部审核确认").is_visible():
                    page.get_by_role("button", name=" 全部审核确认").click()
                    page.get_by_role("button", name="同意", exact=True).click()
                    expect(page.get_by_role("paragraph")).to_contain_text("审核确认成功!")
                    page.wait_for_timeout(3000)
                    page.get_by_role("tab", name="计量报表").click()
                    if page.get_by_role("button", name="生成").is_visible():
                        #page.get_by_role("button", name="生成").click()
                        page.locator("button:nth-child(3)").first.click()
                        if page.get_by_role("row", name="序号 报表名称 上次修改时间").locator("span").nth(1).is_visible():
                            page.get_by_role("row", name="序号 报表名称 上次修改时间").locator("span").nth(1).click()
                            page.get_by_role("button", name="确定").click()
                            page.wait_for_timeout(1000)
                            expect(page.get_by_role("paragraph")).to_contain_text("生成成功")
                            page.wait_for_timeout(2000)
                        else:
                            page.get_by_role("button", name="Close").click()

                    # page.get_by_role("button", name="通 过").click()
                    # expect(page.get_by_role("paragraph")).to_contain_text("审批成功!")

            elif tips == "请生成报表并确认":
                # 手动签字盖章
                page.wait_for_timeout(2000)
                if page.get_by_role("button", name="批量确认").is_visible():
                    page.get_by_role("row", name="序号 报表名称 确认状态 确认人 确认时间 创建时间 操作").locator(
                        "span").nth(1).click()
                    page.get_by_role("button", name="批量确认").click()
                    expect(page.get_by_role("paragraph")).to_contain_text("报表确认成功")
                    page.wait_for_timeout(2000)
                    # page.get_by_role("button", name="通 过").click()
                    # expect(page.get_by_role("paragraph")).to_contain_text("审批成功!")

            elif tips == "请生成报表":
                page.wait_for_timeout(2000)
                page.get_by_role("tab", name="计量报表").click()
                if page.get_by_role("button", name="生成").is_visible():
                    page.get_by_role("button", name="生成").click()
                    page.get_by_role("row", name="序号 报表名称 上次修改时间").locator("span").nth(1).click()
                    page.get_by_role("button", name="确定").click()
                    expect(page.get_by_role("paragraph")).to_contain_text("生成成功")
                    page.wait_for_timeout(2000)
                    page.get_by_role("tab", name="凭证列表").click()
                    page.wait_for_timeout(500)
                    if page.get_by_role("button", name=" 全部审核确认").is_visible():
                        page.get_by_role("button", name=" 全部审核确认").click()
                        page.get_by_role("button", name="同意", exact=True).click()
                        expect(page.get_by_role("paragraph")).to_contain_text("审核确认成功!")
                        page.wait_for_timeout(2000)
                        # page.get_by_role("button", name="通 过").click()
                        # expect(page.get_by_role("paragraph")).to_contain_text("审批成功!")
            ###########################质量验评###########################
            elif tips == "请先填报监理平行下的验评表":
                # 在线表单填报
                # page.locator("div").filter(has_text=re.compile(r"^测量方案报审$")).first.click()
                page.get_by_role("tab", name="相关资料").click()
                page.get_by_role("tab", name="监理平行检").click()
                trcount =  page.get_by_label("监理平行检").locator("//table/tbody/tr").count()
                print("监理平行检：" + str(trcount))
                for tr in page.get_by_label("监理平行检").locator("//table/tbody/tr").all():
                    if page.get_by_role("row", name="未填报").is_visible():
                        page.get_by_role("row", name="未填报").get_by_role("button", name="填报").click()
                        page.wait_for_timeout(1000)
                        if page.get_by_role("button", name="保存").is_visible():
                            page.get_by_role("button", name="保存").click()
                            # expect(page.get_by_label("表单信息").get_by_role("alert")).to_contain_text("保存成功")
                            page.wait_for_timeout(1000)

            if page.get_by_role("button", name="通 过").is_visible():
                page.get_by_role("button", name="通 过").click()
                # 质量验评
                page.wait_for_timeout(1000)
                if page.get_by_text("当前报表是否已经填报？").is_visible():
                    page.get_by_role("button", name="确定").click()
                # 质量验评
                # 测试结果截图
                page.wait_for_timeout(1000)
                filename = os.path.join(test_screenshot_dir, f"{flowtitle}.png")
                page.screenshot(path=filename)
                allure.attach.file(source=filename, name=flowtitle,
                                   attachment_type=allure.attachment_type.PNG)

                tips = page.locator("xpath=//p[@class=\"el-message__content\"]").text_content()  # 获取元素上的文本
                if tips == "请求成功":
                    expect(page.locator("body")).to_contain_text("请求成功")
                elif tips == "审批成功!":
                    expect(page.locator("body")).to_contain_text("审批成功!")
                else:
                    expect(page.locator("body")).to_contain_text("请求成功")


        elif page.get_by_role("button", name="确认阅读").is_visible():
            page.get_by_role("button", name="确认阅读").click()
            expect(page.locator("body")).to_contain_text("请求成功")

    return page
        # 重新获取流程接口最新数据
        #response = httpcontext.get(url=geturl(page), headers=head)
        #responsejson = response.json()
        # 6.解析接口获取审批人
        # 7.审批人转换为账号
        # 8.登录审批人账号，进行审批（通过cookies登录）
        # 9.解析接口获取不到审批人，结束
